import { ref, reactive } from 'vue'
import { defineStore } from 'pinia'
import { 
  getSameEurope293AnalysisApi,
  getMatchPredictEurope18wReturnTestStatisticsApi,
  getFootballEuropeOddsApi
} from "@/pages/europe18w/apis"
import type { 
  MatchPredictEurope18wReturnTestStatisticsCondition,
  MatchPredictEurope18wReturnTestStatisticsResponse,
  MatchPredictEurope18wReturnTestStatistics,
  FootballEuropeOdds,
  FootballEuropeOddsCondition
} from "@/pages/europe18w/apis/type"
import { PaginationRequest } from "@/models/matchPredictEurope18wan"

export const useEuropeReturnTestStore = defineStore("europeReturnTest", () => {
  // 响应式数据
  const isSearchCollapsed = ref(false)
  const loading = ref(false)
  const tableData = ref<any[]>([]) // V293InitSameEuropeFinal[] type
  const total = ref(0)
  const currentPage = ref(1)
  const statisticsData = ref<MatchPredictEurope18wReturnTestStatistics | null>(null)
  // Sorting properties
  const sortField = ref<string | null>(null)
  const sortOrder = ref<'ascending' | 'descending' | null>(null)

  // 搜索表单
  const searchForm = reactive<MatchPredictEurope18wReturnTestStatisticsCondition & PaginationRequest>({
    current_page: 1,
    page_size: 20,
    event_name: null,
    home_initial_min: null,
    home_initial_max: null,
    draw_initial_min: null,
    draw_initial_max: null,
    away_initial_min: null,
    away_initial_max: null,
    home_diff_min: null,
    home_diff_max: null,
    draw_diff_min: null,
    draw_diff_max: null,
    away_diff_min: null,
    away_diff_max: null
  })

  // 方法
  function toggleSearch() {
    isSearchCollapsed.value = !isSearchCollapsed.value
  }

  async function handleSearch() {
    // 设置当前页为第一页
    searchForm.current_page = 1
    currentPage.value = 1
    
    // 清除排序状态
    sortField.value = null
    sortOrder.value = null

    // 查询统计数据
    await fetchStatistics()
    // 查询表格数据
    await fetchData()
  }

  function handleReset() {
    // 重置表单
    searchForm.event_name = null
    searchForm.home_initial_min = null
    searchForm.home_initial_max = null
    searchForm.draw_initial_min = null
    searchForm.draw_initial_max = null
    searchForm.away_initial_min = null
    searchForm.away_initial_max = null
    searchForm.home_diff_min = null
    searchForm.home_diff_max = null
    searchForm.draw_diff_min = null
    searchForm.draw_diff_max = null
    searchForm.away_diff_min = null
    searchForm.away_diff_max = null

    // 重置分页
    searchForm.current_page = 1
    searchForm.page_size = 20
    currentPage.value = 1
    total.value = 0
    tableData.value = []
    statisticsData.value = null
    
    // 重置排序
    sortField.value = null
    sortOrder.value = null
  }

  async function handleSizeChange(size: number) {
    searchForm.page_size = size
    searchForm.current_page = 1
    currentPage.value = 1
    await fetchData()
  }

  async function handleCurrentChange(page: number) {
    searchForm.current_page = page
    currentPage.value = page
    await fetchData()
  }

  async function fetchStatistics() {
    try {
      const condition: MatchPredictEurope18wReturnTestStatisticsCondition = {
        event_name: searchForm.event_name || undefined,
        home_initial_min: searchForm.home_initial_min || undefined,
        home_initial_max: searchForm.home_initial_max || undefined,
        draw_initial_min: searchForm.draw_initial_min || undefined,
        draw_initial_max: searchForm.draw_initial_max || undefined,
        away_initial_min: searchForm.away_initial_min || undefined,
        away_initial_max: searchForm.away_initial_max || undefined,
        home_diff_min: searchForm.home_diff_min || undefined,
        home_diff_max: searchForm.home_diff_max || undefined,
        draw_diff_min: searchForm.draw_diff_min || undefined,
        draw_diff_max: searchForm.draw_diff_max || undefined,
        away_diff_min: searchForm.away_diff_min || undefined,
        away_diff_max: searchForm.away_diff_max || undefined
      }

      const response: MatchPredictEurope18wReturnTestStatisticsResponse =
        await getMatchPredictEurope18wReturnTestStatisticsApi(condition)

      if (response.code === 0) {
        statisticsData.value = response.data
      } else {
        console.error(response.message || '统计数据查询失败')
        statisticsData.value = null
      }
    } catch (error) {
      console.error('统计数据查询失败:', error)
      statisticsData.value = null
    }
  }

  async function fetchData() {
    try {
      loading.value = true

      const condition: any = { // SameEurope293AnalysisCondition
        current_page: searchForm.current_page,
        page_size: searchForm.page_size,
        event_name: searchForm.event_name || undefined,
        fid: undefined, // Not using fid in this case
        home_initial_min: searchForm.home_initial_min || undefined,
        home_initial_max: searchForm.home_initial_max || undefined,
        draw_initial_min: searchForm.draw_initial_min || undefined,
        draw_initial_max: searchForm.draw_initial_max || undefined,
        away_initial_min: searchForm.away_initial_min || undefined,
        away_initial_max: searchForm.away_initial_max || undefined,
        home_diff_min: searchForm.home_diff_min || undefined,
        home_diff_max: searchForm.home_diff_max || undefined,
        draw_diff_min: searchForm.draw_diff_min || undefined,
        draw_diff_max: searchForm.draw_diff_max || undefined,
        away_diff_min: searchForm.away_diff_min || undefined,
        away_diff_max: searchForm.away_diff_max || undefined,
        status: '4' // Add status parameter with value '4'
      }

      const response: any = // V293InitSameEuropeFinalResponse
        await getSameEurope293AnalysisApi(condition)

      if (response.code === 0) {
        tableData.value = response.data || []
        total.value = response.pagination?.total || 0
        currentPage.value = response.pagination?.current_page || 1

        // 保存原始数据，用于排序
        originalTableData.length = 0
        originalTableData.push(...tableData.value)

        // 如果当前有排序，则应用排序
        if (sortField.value && sortOrder.value) {
          sortTableData(sortField.value, sortOrder.value)
        }
      } else {
        console.error(response.message || '查询失败')
      }
    } catch (error) {
      console.error('查询数据失败:', error)
    } finally {
      loading.value = false
    }
  }

  // 初始化页面数据
  async function initializePage() {
    await handleSearch()
  }

  // 获取赔率详情数据
  async function getOddsDataByFid(fid: number) {
    try {
      const condition: FootballEuropeOddsCondition = {
        fid: fid
      }
      
      const response = await getFootballEuropeOddsApi(condition)
      
      if (response.code === 0) {
        return response.data || []
      } else {
        console.error(response.message || '赔率数据查询失败')
        return []
      }
    } catch (error) {
      console.error('赔率数据查询失败:', error)
      return []
    }
  }

  // 处理排序变化
  function handleSortChange({ column, prop, order }: { column?: any, prop: string, order: 'ascending' | 'descending' | null }) {
    if (!order) {
      // 如果没有排序，则重置排序参数
      sortField.value = null
      sortOrder.value = null
      // 重置数据到原始状态
      tableData.value = [...originalTableData]
    } else {
      sortField.value = prop
      sortOrder.value = order
      // 对当前数据进行排序
      sortTableData(prop, order)
    }
  }

  // 存储原始数据
  const originalTableData: any[] = []

  // 保存原始数据并排序
  function sortTableData(prop: string, order: 'ascending' | 'descending') {
    // 保持原始数据的副本
    originalTableData.length = 0
    originalTableData.push(...tableData.value)

    // 根据字段和顺序对数据进行排序
    tableData.value.sort((a, b) => {
      let val1 = a[prop]
      let val2 = b[prop]

      // 处理数字类型值
      if (typeof val1 === 'number' && typeof val2 === 'number') {
        if (order === 'ascending') {
          return val1 - val2
        } else {
          return val2 - val1
        }
      }

      // 处理字符串类型值
      if (typeof val1 === 'string' && typeof val2 === 'string') {
        if (order === 'ascending') {
          return val1.localeCompare(val2)
        } else {
          return val2.localeCompare(val1)
        }
      }

      // 处理其他类型，转换为字符串比较
      val1 = String(val1 || '')
      val2 = String(val2 || '')
      
      if (order === 'ascending') {
        return val1.localeCompare(val2)
      } else {
        return val2.localeCompare(val1)
      }
    })
  }

  return {
    // State
    isSearchCollapsed,
    loading,
    tableData,
    total,
    currentPage,
    statisticsData,
    searchForm,

    // Actions
    toggleSearch,
    handleSearch,
    handleReset,
    handleSizeChange,
    handleCurrentChange,
    fetchStatistics,
    fetchData,
    initializePage,
    getOddsDataByFid,
    handleSortChange
  }
})